package com.lv.jie.utils;

import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author dell
 */
@Component("upload")
public class Upload {
    private String filePath="D:\\UploadFile\\File\\";

    private String ip="127.0.0.1";

    private String port="8080";

    private String location="/file/";

    private static final List<String> CONTENT_TYPES = Arrays.asList(".mp4",".avi",".");

    public  String getRandomFileName() {

        SimpleDateFormat simpleDateFormat;

        simpleDateFormat = new SimpleDateFormat("yyyyMMdd");

        Date date = new Date();

        String str = simpleDateFormat.format(date);

        Random random = new Random();

        // 获取5位随机数
        int ranNum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;
        // 当前时间
        return ranNum + str;
    }

    public String uploadFile(MultipartFile file) throws IOException {
        if(file.isEmpty()){
            return null;
        }
        String prefixFileName =getRandomFileName();
        String originalName=file.getOriginalFilename();
        String suffix = Objects.requireNonNull(originalName).substring(originalName.lastIndexOf('.'));
        if(!CONTENT_TYPES.contains(suffix)){
            return null;
        }
        String fileName=prefixFileName+suffix;
        File dest = new File(filePath+fileName);
        file.transferTo(dest);
        return "http://"+ip+":"+port+location+fileName;
    }
}
